<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="装备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入装备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="装备类别" prop="category">
        <el-input
          v-model="queryParams.category"
          placeholder="请输入装备类别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库编号" prop="warehouseId">
        <el-input
          v-model="queryParams.warehouseId"
          placeholder="请输入仓库编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equipment:equipment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:equipment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment:equipment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equipment:equipment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="装备ID" align="center" prop="id" />
      <el-table-column label="装备名称" align="center" prop="equipmentName" />
      <el-table-column label="装备类别" align="center" prop="category" />
      <el-table-column label="装备状态" align="center" prop="statusLabel" />
      <el-table-column label="派出状态" align="center" prop="dispatchStatusLabel" />
      <el-table-column label="所在仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:equipment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:equipment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改装备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="装备名称" prop="equipmentName">
          <el-input v-model="form.equipmentName" placeholder="请输入装备名称" />
        </el-form-item>
        <el-form-item label="装备类别" prop="category">
          <el-input v-model="form.category" placeholder="请输入装备类别" />
        </el-form-item>
         <el-form-item label="装备状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in equipmentOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel" 
              :value="dict.dictValue" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="派出状态" prop="dispatchStatus">
          <el-select v-model="form.dispatchStatus" placeholder="请选择状态">
            <el-option
              v-for="dict in dispatchOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel" 
              :value="dict.dictValue" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select v-model="form.warehouseId" placeholder="请选择仓库">
            <el-option
              v-for="warehouse in warehouseList"
              :key="warehouse.id"
              :label="warehouse.name" 
              :value="warehouse.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment } from "@/api/equipment/equipment";
import { listWarehouse } from "@/api/warehouse/warehousemanagement";

export default {
  name: "Equipment",
  data() {
    return {
      addflag:false,
      warehouseMap: {}, // 仓库ID到名称的映射
      warehouseList: [], // 仓库列表
      dispatchOptions:[],
      equipmentOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 装备管理表格数据
      equipmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentName: null,
        category: null,
        status: null,
        dispatchStatus: null,
        warehouseId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        equipmentName: [
          { required: true, message: "装备名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态(1:正常 2:维修 3:报废)不能为空", trigger: "change" }
        ],
      }
    }
  },
  created() {
    // 先获取仓库列表，确保在获取装备列表前仓库映射已建立
    this.getWarehouseList().then(() => {
    // 使用Promise.all确保两个字典都加载完成
    return Promise.all([
      this.getDicts("dispatch_status"),
      this.getDicts("equipment_status")
    ]);
  }).then(([dispatchRes, equipmentRes]) => {
    this.dispatchOptions = dispatchRes.data;
    this.equipmentOptions = equipmentRes.data;
    // 最后获取装备列表
    this.getList();
    });
  },
  methods: {
    // 获取仓库列表并建立映射
    getWarehouseList() {
      return new Promise((resolve, reject) => {
        // 调用后端仓库列表接口
        listWarehouse().then(response => {
          this.warehouseList = response.data || [];
          // 建立仓库ID到名称的映射
          this.warehouseMap = this.warehouseList.reduce((map, warehouse) => {
            map[warehouse.id] = warehouse.name;
            return map;
          }, {});
          resolve();
        }).catch(error => {
          console.error('获取仓库列表失败', error);
          reject(error);
        });
      });
    },

    /** 查询装备管理列表 */
    getList() {
      this.loading = true;
      listEquipment(this.queryParams).then(response => {
        // 处理装备列表，添加仓库名称字段
        this.equipmentList = (response.rows || []).map(item => {
          // 根据warehouseId获取对应的仓库名称，如果没有则显示未知
          item.warehouseName = this.warehouseMap[item.warehouseId] || '未知';

          const statusDict = this.equipmentOptions.find(
          dict => dict.dictValue === String(item.status) // 转换为字符串
        );
          item.statusLabel = statusDict ? statusDict.dictLabel : '未知状态';
          // 处理派出状态 - 添加相同逻辑
          const dispatchDict = this.dispatchOptions.find(
          dict => dict.dictValue === String(item.dispatchStatus)
        );
          item.dispatchStatusLabel = dispatchDict ? dispatchDict.dictLabel : '未知状态';

          return item;
        });
        this.total = response.total || 0;
        this.loading = false;
      }).catch(error => {
        console.error('获取装备列表失败', error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        equipmentName: null,
        category: null,
        status: null,
        createTime: null,
        updateTime: null,
        dispatchStatus: null,
        warehouseId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addflag = true;
      this.open = true;
      this.title = "添加装备管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getEquipment(id).then(response => {
        this.form = response.data;
        this.addflag = false;
        this.open = true;
        this.title = "修改装备管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.addflag) {
            updateEquipment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEquipment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除装备管理编号为"' + ids + '"的数据项？').then(function() {
        return delEquipment(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('equipment/equipment/export', {
        ...this.queryParams
      }, `equipment_${new Date().getTime()}.xlsx`);
    }
  }
}
</script>